package com.itheima.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.itheima.mp.domain.dto.PageDTO;
import com.itheima.mp.domain.po.Address;
import com.itheima.mp.domain.po.User;
import com.itheima.mp.domain.query.UserQuery;
import com.itheima.mp.domain.vo.AddressVO;
import com.itheima.mp.domain.vo.UserVO;
import com.itheima.mp.enums.UserStatus;
import com.itheima.mp.mapper.UserMapper;
import com.itheima.mp.service.IUserService;
import org.apache.ibatis.annotations.ResultType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author YUBOY
 * @date 2025/1/12
 * @Description
 */
@Service // 表示当前类是一个服务类
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    //此时不用注入UserMapper userService
    //表示继承Mybatis-Plus服务实现类

    @Override
    @Transactional
    public void deductBanlance(Long userId, Integer money) {
        //1.查询用户
        User user = this.getById(userId);
        //2.检查用户状态
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常!");
        }
        //3.检查余额是否足够
        if (user.getBalance() < money) {
            throw new RuntimeException("余额不足!");
        }
        //4.更新余额
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance)
                .set(remainBalance == 0, User::getStatus, UserStatus.FROZEN)
                .eq(User::getId, userId)
                .eq(User::getBalance, user.getBalance()) //乐观锁 防止并发安全问题
                .update();
    }

    @Override
    public List<User> queryUsers(String name, Integer status, Integer minBalance, Integer maxBalance) {

        return lambdaQuery().like(name != null, User::getUsername, name).
                eq(status != null, User::getStatus, status)
                .ge(minBalance != null, User::getBalance, minBalance).
                le(maxBalance != null, User::getBalance, maxBalance)
                .list();
    }

    @Override
    @Transactional
    public UserVO queryUserAndAddress(Long id) {
        //1.查询用户
        User user = this.getById(id);
        if (user == null || user.getStatus() == UserStatus.FROZEN) {
            throw new RuntimeException("用户状态异常!");
        }
        //2.查询地址
        List<Address> list = Db.lambdaQuery(Address.class)
                .eq(Address::getUserId, id)
                .list();
        //3.封装VO
        UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
        //转地址VO
        if (CollUtil.isNotEmpty(list)) {
            userVO.setAddressList(BeanUtil.copyToList(list, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> listQueryUserAndAddress(List<Long> ids) {
        //1.查询用户
        List<User> users = this.listByIds(ids);
        if(CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        //2.查询地址
        List<Long> userIds= users.stream().map(User::getId).collect(Collectors.toList());
        List<Address> list = Db.lambdaQuery(Address.class)
                .in(Address::getUserId, userIds)
                .list();
        //转换地址VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(list, AddressVO.class);
        //梳理地址集合，分组封装
        Map<Long, List<AddressVO>> addressMap = new HashMap<>(0);
        if(CollUtil.isNotEmpty(addressVOS)) {
            addressMap= addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }
        //3.转化VO
        List<UserVO> userVOS = new ArrayList<>();
        for (User user : users) {
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVOS.add(userVO);
            //转换地址VO
            userVO.setAddressList(addressMap.get(user.getId()));
        }
        return userVOS;
    }

    @Override
    public PageDTO<UserVO> queryUserByPages(UserQuery userQuery) {
        //1.构建查询条件
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
//        //分页条件
//        Page<User> page = Page.of(userQuery.getPageNo(), userQuery.getPageSize());
//        //排序条件
//        if(userQuery.getSortBy() != null) {
//            page.addOrder(new OrderItem(userQuery.getSortBy(),userQuery.getIsAsc()));//表示根据字段排序
//        }else {
//            page.addOrder(new OrderItem("create_time",true));
//            //如果排序字段为空 表示根据创建时间降序排序
//        }
        Page<User> page = userQuery.toMpPageDefaultSortByCreateTimeDesc();//表示根据创建时间降序排序
        //2.进行分页查询
        Page<User> p = lambdaQuery().like(name != null, User::getUsername, name).
                eq(status != null, User::getStatus, status)
                .page(page);
        //3.封装数据
//        PageDTO<UserVO> pageDTO = new PageDTO<>();
//        pageDTO.setTotal(p.getTotal()); //表示总记录数
//        pageDTO.setPages(p.getPages()); //表示总页数
//        List<User> records = p.getRecords();
//        if(CollUtil.isEmpty(records)) {
////            如果没有数据直接返回空数据即可
//            pageDTO.setList(Collections.emptyList());
//            return pageDTO;
//        }
//        List<UserVO> userVOS = BeanUtil.copyToList(records, UserVO.class);
//        //copyToList表示将records集合中的数据复制到UserVO集合中
//        pageDTO.setList(userVOS);
        return PageDTO.of(p,user ->BeanUtil.copyProperties(user,UserVO.class)); //使用封装好的方法进行封装  减少冗余代码
    }

}
